package com.dq.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dq.utils.MessageUtil;
import com.dq.vo.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: chat-backend-public_小强 (QQ:2680825683)
 * @className: ChatEndpoint
 * @since: 2023/2/9 17:45
 */
@ServerEndpoint(value = "/chat/{username}")
@Component
@Slf4j
public class ChatEndpoint {

    //建议一个单一化的容器存储class  注意并发所带来的Map混乱
    private static Map<String, Session> onlineUser = new ConcurrentHashMap<>();

    /**
     * 链接建立时执行
     *
     * @param session
     * @param username
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        onlineUser.put(username, session);
        log.info("有新用户加入  username={},当前在线人数为:{}", username, onlineUser.size());
        //将当前对象存储至线程中(登录成功的用户)
        sendAllMessage(setUserList(username,true));
    }


    /**
     * 链接关闭调用
     *
     * @param username
     */
    @OnClose
    public void OnClose(@PathParam("username") String username) {
        onlineUser.remove(username);
        sendAllMessage(setUserList(username,false));
    }

    /**
     * 接收到客户端发送数据时捕获调用
     *
     * @param message
     */
    @OnMessage
    public void OnMessage(String message) {
        Message msg = JSON.parseObject(message, Message.class);
        msg.setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        if (StringUtils.isEmpty(msg.getTo())) {
            sendAllMessage(JSON.toJSONString(msg));
        } else {
            Session sessionTo = onlineUser.get(msg.getTo());
            sendMessage(message, sessionTo);
        }
    }

    public void onError(Session session ,Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 获取所有用户用于推送
     *
     * @return
     */
    private String setUserList(String person,boolean isJoin) {
        ArrayList<String> arrayList = new ArrayList<>();
        for (String name : onlineUser.keySet()) {
            arrayList.add(name);
        }
        Message message = new Message();
        message.setUserNames(arrayList);
        if (isJoin){
            message.setJoinPerson(person);
        }else {
            message.setLeavePerson(person);
        }
        return JSON.toJSONString(message);
    }

    /**
     * 单独发送
     *
     * @param message
     * @param session
     */
    private void sendMessage(String message, Session session) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 系统推送方法
     *
     * @param message
     */
    private void sendAllMessage(String message) {
        try {
            for (Session session : onlineUser.values()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
